#include <hd_led.h>
#include <hd_oled_protocol_i2c.h>
#include <hd_oled.h>
#include <delay.h>
#include <pd_adc.h>
#include <pd_adc_reg.h>
#include <stddef.h>
#include <pd_i2c_hd.h>
#include "main.h"

#define ARRAY_SIZE(x)       sizeof(x) / sizeof(x[0])
#define USE_HARDWARE_SPI    1
#define USE_HARDWARE_I2C    1
uint16_t num;
LED led;
OLED oled;

extern void SystemClock_Config(void);

void oled_instance(OLED *oled);

int main(void) {
    SystemClock_Config();

    NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2);

    oled_instance(&oled);

    OLED_printf(&oled, 0, 00, "ADC");
    OLED_printf(&oled, 0, 16, "ADValue:");
    OLED_printf(&oled, 0, 32, "Voltage:0.00V");

    // PC0 -- ADC123_IN10
    GPIO adcGPIO[1];
    GPIO_constructor(adcGPIO + 0, GPIOC, LL_GPIO_PIN_0);

    ADCChannel adcChannel;
    ADCChannel_constructor(&adcChannel, adcGPIO, ARRAY_SIZE(adcGPIO), NULL, 0, NULL, 0);

    ADCBase adcBase;
    ADCBase_constructor(&adcBase, ADC1, &adcChannel, LL_ADC_SEQ_SCAN_DISABLE);

    ADCRegular adcRegular;
    ADCRegular_constructor(&adcRegular, &adcBase, LL_ADC_REG_TRIG_SOFTWARE, LL_ADC_REG_SEQ_SCAN_DISABLE,
                           LL_ADC_REG_CONV_SINGLE, LL_ADC_REG_DMA_TRANSFER_NONE);
    ADCRegular_init(&adcRegular);

    while (1) {
        const uint16_t ad = ADCRegular_getValue(&adcRegular, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_10,
                                                LL_ADC_SAMPLINGTIME_56CYCLES);
        const float voltage = (float)ad / 4095 * 3.3;

        OLED_printf(&oled, 64, 16, "%4d", ad);
        OLED_printf(&oled, 64, 32, "%1d", (uint32_t)voltage);
        OLED_printf(&oled, 80, 32, "%02d", (uint16_t)(voltage * 100) % 100);
        OLED_refresh(&oled);

        delay_ms(100);
    }
}


void oled_instance(OLED *oled) {
    // I2C gpio init
    static GPIO oledSckGPIO, oledSdaGPIO;
    GPIO_constructor(&oledSckGPIO, GPIOB, LL_GPIO_PIN_10); // I2Cx_SCK
    GPIO_constructor(&oledSdaGPIO, GPIOB, LL_GPIO_PIN_11); // I2Cx_SDA

#ifdef USE_HARDWARE_I2C
    static I2CHardware i2c2;
    I2CHardware_constructor(&i2c2, I2C2, &oledSckGPIO, &oledSdaGPIO);
#elif USE_SIMULATE_I2C
    static I2CSimulate i2c2;
    I2CSimulate_constructor(&i2c2, &oledSckGPIO, &oledSdaGPIO);
#endif
    I2C_init((I2C *)&i2c2);

    // OLED protocol of I2C
    static OLEDProtocolI2C oledProtocolI2c;
    OLEDProtocolI2C_constructor(&oledProtocolI2c, (I2C *)&i2c2);

    // OLED font instance.
    static OLEDFont oledFont;
    OLEDFont_contructor(&oledFont, NULL);

    // OLED instance of 4-PIN(I2C)
    OLED_constructor(oled, (OLEDProtocol *)&oledProtocolI2c, &oledFont);

    OLED_init(oled);

    OLED_clear(oled);
    OLED_refresh(oled);
}
